package org.smile.config;

import org.smile.io.IOUtils;
import org.smile.template.SimpleStringTemplate;
import org.smile.template.Template;
import org.smile.util.XmlUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

public class XmlProperties extends YmlProperties {
    /**
     * 根结点标签
     */
    protected String root = "config";

    @Override
    public void load(InputStream is, Object initParam, boolean closeIs) throws IOException {
        try {
            String xml = IOUtils.readString(is);
            if (initParam != null) {
                Template template = new SimpleStringTemplate(xml);
                xml = template.processToString(initParam);
            }
            Map<String, Object> result = XmlUtils.parseXmlToMap(xml);
            Map config = (Map) result.get(root);
            if (config != null) {
                putAll(config);
            } else {
                throw new NullPointerException("不存在的根结点:" + root);
            }
        } finally {
            if (closeIs) {
                IOUtils.close(is);
            }
        }
    }

    public void setRoot(String root) {
        this.root = root;
    }

}
